//
//  XMMyOrderTopTabView.m
//  XMJJ_zml
//
//  Created by 丁浩 on 2025/5/26.
//

#import "XMMyOrderTopTabView.h"

@interface XMMyOrderTopTabView ()

@property (nonatomic, strong) NSMutableArray *itemBtnArr;
@property (nonatomic, strong) NSArray *titleArr;
@property (nonatomic, strong) UIView *lineView;

@property (nonatomic, assign) CGFloat fontSize;

@end

@implementation XMMyOrderTopTabView

- (instancetype)initWithFrame:(CGRect)frame
                     titleArr:(NSArray *)titleArr
                        space:(CGFloat)space
                    lineColor:(UIColor *)lineColor
                    lineWidth:(CGFloat)lineWidth
                     fontSize:(CGFloat)fontSize
                   titleColor:(nonnull UIColor *)titleColor
                  selectColor:(nonnull UIColor *)selectColor{
    self = [super initWithFrame:frame];
    if (self) {
        _fontSize = fontSize;
        if (lineWidth > 0) {
            CGFloat frameY = (self.height - fontSize)/2*1.5 + fontSize;
            _lineView = [[UIView alloc] initWithFrame:CGRectMake(0, frameY, lineWidth, 2)];
            _lineView.backgroundColor = lineColor;
            [self addSubview:self.lineView];
        }
        CGFloat itemWidth = (self.width - space*2)/titleArr.count;
        for (int i = 0; i < titleArr.count; i ++) {
            UIButton *itemBtn = [UIButton buttonWithType:UIButtonTypeCustom font:KFontSize(fontSize) frame:CGRectMake(space + itemWidth*i, 0, itemWidth, self.height - 2) title:titleArr[i] selectTitle:titleArr[i] titleColor:titleColor selectColor:selectColor];
            [itemBtn addTarget:self action:@selector(itemSelectAction:) forControlEvents:UIControlEventTouchUpInside];
            [self addSubview:itemBtn];
            [self.itemBtnArr addObject:itemBtn];
            if (i == 0) {
                itemBtn.selected = YES;
                itemBtn.titleLabel.font = KBoldFontSize(fontSize);
                _lineView.x = space + (itemWidth - lineWidth)/2;
            }
            itemBtn.tag = 10000 + i;
        }
    }
    return self;
}

- (void)itemSelectAction:(UIButton *)button {
    for (UIButton *itemBtn in self.itemBtnArr) {
        itemBtn.selected = NO;
        itemBtn.titleLabel.font = KFontSize(_fontSize);
    }
    button.selected = YES;
    button.titleLabel.font = KBoldFontSize(_fontSize);
    XMWeakSelf;
    [UIView animateWithDuration:.3 animations:^{
        weakSelf.lineView.x = button.x + (button.width - weakSelf.lineView.width)/2;
    }];
    self.itemSelectBlock ? self.itemSelectBlock(button.tag - 10000) : nil;
}

- (NSMutableArray *)itemBtnArr {
    if (!_itemBtnArr) {
        _itemBtnArr = [NSMutableArray array];
    }
    return _itemBtnArr;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
